<!-- 监督决定 -->
<template>
  <a-card class="case_produce">
    <a-spin :spinning="spinning">
      <div style="margin-bottom: 15px">
        <!-- <span class="add_form_label"> 监督决定 </span> -->
        <!-- 当前是编辑模式 -->
        <a-button
          v-if="isEditModel && this.category == 'decision'"
          class="add_form_btn btn_primary_color"
          style="margin: -25px 0px 10px 0px"
          type="primary"
          :disabled="btnDisabled"
          @click="startBusinessProcedClick"
          :loading="loading"
        >
          监督决定申请
        </a-button>
        <!-- <a-divider /> -->
      </div>

      <div style="margin-top: 40px">
        <!-- <a-icon class="file_icon" slot="avatar" type="file-text" /> -->
        <div class="file_title">
          <span class="upload_span">调查结果材料</span>
          <!-- <a-button class="upload_btn" @click="specialUpload(3)"> <a-icon type="upload" />上传</a-button> -->
          <div class="upload_text" @click="specialUpload(3)">
            <a-icon type="upload" :style="{ color: '#0072C6', paddingRight: '10px', paddingTop: '2px' }" />&emsp;&emsp;
            上传
          </div>
        </div>
        <div class="pdf_text" v-if="resultFileList && resultFileList.length > 0">
          <div class="upload_list_div" v-for="(fileItem, index) in resultFileList" :key="index">
            <a class="upload_list_dropdown ant-dropdown-link" @click="e => e.preventDefault()">
              <a-icon :style="{ color: '#0072c6' }" type="link" style="font-size: 14px" />
              <a
                type="link"
                class="upload_list_item_name beyond_hiding"
                :title="fileItem.filename"
                :key="index"
                @click="fileItem.isEditor ? null : handleClick(fileItem, index)"
                @dblclick.prevent="handleDoubleClick(fileItem, index)"
              >
                <!-- 添加重命名输入框，根据fileItem.isEditor状态显示 -->
                <input
                  :ref="`input${index}`"
                  v-show="fileItem.isEditor"
                  type="text"
                  class="transparent-input"
                  v-model="newFilename"
                  :key="index"
                  autofocus
                  @blur="saveFileName(fileItem)"
                  @keydown.enter="saveFileName(fileItem)"
                />

                <span style="color: #0072c6" v-show="!fileItem.isEditor">{{ fileItem.filename }}</span>
              </a>
              <a-dropdown :trigger="['click']" v-show="isEditModel">
                <a
                  class="ant-dropdown-link"
                  style="display: inline-block; width: 70px; margin-left: 20px; margin-left: 20px; color: #000"
                  @click="e => e.preventDefault()"
                  >操作<a-icon type="down" style="padding-left: 10px"
                /></a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a style="display: block" @click="downloadFile(fileItem)">下载</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a style="display: block" @click="specialRemove(fileItem)">删除</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a style="display: block" @click="weboffice(currentUser.userId, applyid, fileItem)">在线编辑</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a style="display: block" @click="versionView(fileItem)">历史版本</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </a>
          </div>
        </div>
      </div>
      <div style="margin: 10px 0px">
        <a-form layout="inline" class="operate_div">
          <span style="color: red; padding-right: 5px; text-align: center">*</span>
          <a-form-item label="决定类型 ：">
            <a-radio-group v-model="decisionType" :disabled="!isEditModel || btnDisabled" name="radioGroup">
              <a-radio
                v-for="decisionItem in Tp_supervise_decisionList"
                :key="decisionItem.value"
                :value="decisionItem.value"
              >
                {{ decisionItem.name }}
              </a-radio>
              <!-- <a-radio :value="2"> 告知 </a-radio> -->
            </a-radio-group>
          </a-form-item>
        </a-form>
      </div>
      <div style="margin: 10px 0px" v-if="decisionType == Tp_supervise_decisionValue.SUPPORT">
        <div class="operate_div">
          <span style="color: red; padding-right: 5px; text-align: center">*</span>
          <!-- <a-icon class="file_icon" slot="avatar" type="file-text" /> -->
          <div class="file_title">
            <span class="upload_span">通知书</span>
            <!-- <a-button class="upload_btn" @click="specialUpload(1)"> <a-icon type="upload" />上传</a-button> -->
            <div class="upload_text" @click="specialUpload(1)">
              <a-icon
                type="upload"
                :style="{ color: '#0072C6', paddingRight: '10px', paddingTop: '2px' }"
              />&emsp;&emsp; 上传
            </div>
          </div>
        </div>
        <div class="pdf_text" v-if="noticeFileList && noticeFileList.length > 0">
          <div class="upload_list_div" v-for="(fileItem, index) in noticeFileList" :key="index">
            <a class="upload_list_dropdown ant-dropdown-link" @click="e => e.preventDefault()">
              <a-icon :style="{ color: '#0072c6' }" type="link" style="font-size: 14px" />
              <a
                type="link"
                class="upload_list_item_name beyond_hiding"
                :title="fileItem.filename"
                :key="index"
                @click="fileItem.isEditor ? null : handleClick(fileItem, index)"
                @dblclick.prevent="handleDoubleClick(fileItem, index)"
              >
                <input
                  :ref="`input${index}`"
                  v-show="fileItem.isEditor"
                  type="text"
                  class="transparent-input"
                  v-model="newFilename"
                  :key="index"
                  autofocus
                  @blur="saveFileName(fileItem)"
                  @keydown.enter="saveFileName(fileItem)"
                />

                <span style="color: #0072c6" v-show="!fileItem.isEditor">{{ fileItem.filename }}</span>
              </a>
              <a-dropdown :trigger="['click']" v-show="isEditModel">
                <a
                  class="ant-dropdown-link"
                  style="display: inline-block; width: 70px; margin-left: 20px; color: #000"
                  @click="e => e.preventDefault()"
                  >操作<a-icon type="down" style="padding-left: 10px"
                /></a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a style="display: block" @click="downloadFile(fileItem)">下载</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a style="display: block" @click="specialRemove(fileItem)">删除</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a style="display: block" @click="weboffice(currentUser.userId, applyid, fileItem)">在线编辑</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a style="display: block" @click="versionView(fileItem)">历史版本</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </a>
          </div>
        </div>
      </div>

      <div style="margin: 10px 0px">
        <div class="operate_div">
          <span style="color: red; padding-right: 5px; text-align: center">*</span>
          <!-- <a-icon class="file_icon" slot="avatar" type="file-text" /> -->
          <div class="file_title" style="margin-top: -12px">
            <span class="upload_span">告知书</span>
            <!-- <a-button class="upload_btn" @click="specialUpload(2)"> <a-icon type="upload" />上传</a-button> -->
            <div class="upload_text" @click="specialUpload(2)">
              <a-icon
                type="upload"
                :style="{ color: '#0072C6', paddingRight: '10px', paddingTop: '2px' }"
              />&emsp;&emsp; 上传
            </div>
          </div>
        </div>
        <div class="pdf_text" v-if="tellFileList && tellFileList.length > 0">
          <div class="upload_list_div" v-for="(fileItem, index) in tellFileList" :key="index">
            <a class="upload_list_dropdown ant-dropdown-link" @click="e => e.preventDefault()">
              <a-icon :style="{ color: '#0072c6' }" type="link" style="font-size: 14px" />
              <a
                type="link"
                class="upload_list_item_name beyond_hiding"
                :title="fileItem.filename"
                :key="index"
                @click="fileItem.isEditor ? null : handleClick(fileItem, index)"
                @dblclick.prevent="handleDoubleClick(fileItem, index)"
              >
                <!-- 添加重命名输入框，根据fileItem.isEditor状态显示 -->
                <input
                  :ref="`input${index}`"
                  v-show="fileItem.isEditor"
                  type="text"
                  class="transparent-input"
                  v-model="newFilename"
                  :key="index"
                  autofocus
                  @blur="saveFileName(fileItem)"
                  @keydown.enter="saveFileName(fileItem)"
                />

                <span style="color: #0072c6" v-show="!fileItem.isEditor">{{ fileItem.filename }}</span>
              </a>
              <a-dropdown :trigger="['click']" v-show="isEditModel">
                <a
                  class="ant-dropdown-link"
                  style="display: inline-block; width: 70px; margin-left: 20px; color: #000"
                  @click="e => e.preventDefault()"
                  >操作<a-icon type="down" style="padding-left: 10px"
                /></a>
                <a-menu slot="overlay">
                  <a-menu-item>
                    <a style="display: block" @click="downloadFile(fileItem)">下载</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a style="display: block" @click="specialRemove(fileItem)">删除</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a style="display: block" @click="weboffice(currentUser.userId, applyid, fileItem)">在线编辑</a>
                  </a-menu-item>
                  <a-menu-item>
                    <a style="display: block" @click="versionView(fileItem)">历史版本</a>
                  </a-menu-item>
                </a-menu>
              </a-dropdown>
            </a>
          </div>
        </div>
      </div>

      <div style="margin: 10px 0px">
        <a-form layout="inline" class="operate_div">
          <span style="color: red; padding-right: 5px; text-align: center">*</span>
          <a-form-item label="是否需要整改 ：">
            <a-radio-group v-model="radioVal" :disabled="!isEditModel || btnDisabled">
              <a-radio :value="3200"> 是 </a-radio>
              <a-radio :value="3201"> 否 </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </div>
    </a-spin>

    <MultiUploadBasic ref="multiUploadBasic" @importFileFun="importFileFun"></MultiUploadBasic>
    <MaterialVersion ref="materialVersionRef"></MaterialVersion>
  </a-card>
</template>
<script>
import { APP_USER, APP_DEPT } from '@/store/mutation-types.js'
import storage from 'store'
import { viewSupervise, saveSupervise } from '@/api/supervise/apl_supervise.js'
import { kkfilePreview, webofficeEdit, downloadFile } from '@/utils/util.js'
import { minioUpload, minioRemove, minioUploadMore } from '@/api/base/file'
import { Tp_supervise_decisionList, Tp_supervise_decisionValue } from '@/enumeration/Tp_supervise_decision'
import { updateFilename } from '@/api/accept/aprv_materials_options'
import { startBusinessProced } from '@/api/supervise/businesssupervise.js'
import { Tp_proctypeValue } from '@/enumeration/Tp_proctype'
import { saveMaterialRepeat, deleteMaterial, getAllMaterialByApplyId } from '@/api/accept/aprv_process_materials'
import { Tp_procmaterialValue } from '@/enumeration/Tp_procmaterial'

const SUPERVISE_NOTICE = Tp_procmaterialValue.SUPERVISE_NOTICE // 复议监督通知书
const SUPERVISE_TELL = Tp_procmaterialValue.SUPERVISE_TELL // 复议监督告知书
const SUPERVISE_RESULT = Tp_procmaterialValue.SUPERVISE_RESULT // 复议监督调查结果
export default {
  props: {
    applyid: {
      type: String,
      required: true
    },
    category: {
      type: String,
      required: false
    },
    processinstanceid: {
      type: String,
      default: '',
      required: true
    },
    isEditModel: {
      type: Boolean,
      required: true
    }
  },
  data () {
    return {
      operateBtnDisabled: true, // 特殊情况限制按钮
      btnDisabled: true,
      currentUser: storage.get(APP_USER),
      superviseObj: {}, // 复议监督数据
      fileList: [], // 文件列表
      spinning: false, // 加载框
      operateType: 1, // 1: 复议监督通知书 2: 复议监督告知书 3: 复议监督结果材料
      uploadFileType: undefined, // 通知书 还是 告知书
      decisionType: undefined, //  决定类型
      Tp_supervise_decisionList: Tp_supervise_decisionList,
      Tp_supervise_decisionValue: Tp_supervise_decisionValue,
      radioVal: 3201, // 是否需要整改
      busiType: Tp_proctypeValue.SUPERVISE_DECISION,
      clickTimeout: undefined,
      newFilename: '',
      noticeFileList: [], // 复议监督通知书
      tellFileList: [], // 复议监督告知书
      resultFileList: [], // 复议监督结果材料
      loading: false
    }
  },
  components: {
    MultiUploadBasic: () => import('@/views/materials/multiUpload/MultiUploadBasic.vue'),
    MaterialVersion: () => import('@/views/materials/MaterialVersion'),
    SuperviseFeedBack: () => import('@/views/supervise/SuperviseFeedBack.vue')
  },
  async created () {
    if (this.applyid) {
      await this.viewSupervise()
      this.queryMaterialsList()
      if (this.category == 'decision') {
        this.btnDisabled = false
      }
    }
  },
  mounted () {},
  watch: {
    decisionType: {
      handler (val) {},
      immediate: true,
      deep: true
    },
    radioVal: {
      handler (val) {
        this.$emit('changeRadio', val)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    async viewSupervise () {
      let _this = this
      _this.spinning = true
      const res = await viewSupervise(this.applyid).finally(() => {
        this.spinning = false
      })
      // this.spinning = false
      if (res.code === 0) {
        this.superviseObj = res.data ? res.data : {}
        if (_this.superviseObj) {
          this.decisionType = this.superviseObj.decisiontype
          this.radioVal = this.superviseObj.isrectifica
        }
      } else {
        this.$message.error('查询复议监督数据异常')
      }
    },

    specialUpload (type) {
      if (type == 1) {
        this.uploadFileType = SUPERVISE_NOTICE
      } else if (type == 2) {
        this.uploadFileType = SUPERVISE_TELL
      } else if (type == 3) {
        this.uploadFileType = SUPERVISE_RESULT
      }
      this.$refs.multiUploadBasic.importVisible = true
    },
    /**
     * 确定保存导入数据
     */
    importFileFun (importFileList) {
      console.log('importFileList', importFileList)
      const files = []
      importFileList.forEach(item => {
        files.push(item)
      })
      this.$refs.multiUploadBasic.loading = true
      minioUploadMore(files)
        .then(res => {
          if (res.code == 0) {
            const attachs = res.data
            // 更新字段
            this.specialUploadFun(importFileList)
          } else {
            this.$message.success('上传失败')
            this.$refs.multiUploadBasic.handleCancel()
          }
        })
        .finally(() => {
          this.$refs.multiUploadBasic.handleCancel()
        })
    },
    versionView (fileItem) {
      this.$nextTick(() => {
        this.$refs.materialVersionRef.init(fileItem)
      })
    },
    // 在线编辑文书
    weboffice (userid, applyid, file) {
      console.log('file', file)
      const url = `${webofficeEdit(file.url)}&userid=${userid}&applyid=${applyid}&attachid=${file.id}`
      console.log('viewfile', url)
      window.open(url)
    },
    // 附件在线预览
    fileView (file) {
      console.log('文件预览', file)
      window.open(kkfilePreview(file.path))
    },
    // 下载文件
    downloadFile (file) {
      var x = new XMLHttpRequest()
      x.open('GET', file.path, true)
      x.responseType = 'blob'
      x.onload = function (e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a')
        a.href = url
        a.download = file.filename
        a.click()
      }
      x.send()
    },
    // 通知书 告知书文件删除
    specialRemove (file) {
      // 弹出确认框是否删除该文件
      this.$confirm({
        title: '提示',
        content: '确定删除该文件吗？',
        onOk: () => {
          const param = {
            materialId: file.materialId
          }
          this.spinning = true
          deleteMaterial(param)
            .then(res => {
              if (res.code !== 0) {
                this.$message.error(res.msg)
              } else {
                this.queryMaterialsList()
              }
            })
            .catch(err => {
              console.log(err, '获取数据失败')
            })
            .finally(() => {
              setTimeout(() => {
                this.spinning = false
              }, 50)
            })
        }
      })
    },
    // 通知书 告知书文件上传
    specialUploadFun (importFileList) {
      // 上传接口方法
      const param = {
        applyid: this.applyid,
        fileType: this.uploadFileType,
        busiType: this.busiType,
        userId: this.currentUser.userId,
        userName: this.currentUser.fullname
      }
      saveMaterialRepeat(param, importFileList)
        .then(res => {
          if (res.code !== 0) {
            this.$message.error(res.msg)
          } else {
            this.$refs.multiUploadBasic.handleCancel()
            this.queryMaterialsList()
          }
        })
        .catch(err => {
          console.log(err, '上传数据失败')
        })
    },
    // 通知书 告知书 文件查询
    queryMaterialsList () {
      this.spinning = true
      this.noticeFileList = []
      this.tellFileList = []
      this.resultFileList = []
      getAllMaterialByApplyId({ applyid: this.applyid })
        .then(res => {
          // console.log('表格数据:', res.data)
          const records = res.data
          this.allFileList = records
          // 根据对应的分类进行赋值
          this.filteFile()
          console.log('材料文件', this.fileItem)
        })
        .finally(() => {
          this.spinning = false
        })
    },
    // 过滤文件
    filteFile () {
      // 根据对应的分类进行赋值
      if (this.allFileList != null && this.allFileList.length > 0) {
        for (const record of this.allFileList) {
          // 普通的材料
          if (record.type == this.busiType && record.file) {
            const fileDetail = record.file
            fileDetail.materialId = record.id
            fileDetail.name = fileDetail.filename
            fileDetail.status = 'done'
            fileDetail.uid = fileDetail.id
            fileDetail.url = fileDetail.path
            fileDetail.isEditor = false
            if (record.mattype == SUPERVISE_NOTICE) {
              this.noticeFileList.push(fileDetail)
            } else if (record.mattype == SUPERVISE_TELL) {
              this.tellFileList.push(fileDetail)
            } else if (record.mattype == SUPERVISE_RESULT) {
              this.resultFileList.push(fileDetail)
            }
          }
        }
      }
    },
    handleDoubleClick (fileItem, index) {
      // 将材料名先复制给 newFilename 双向绑定到 编辑框上
      this.newFilename = fileItem.filename
      fileItem.isEditor = true // 进入编辑模式
      // 自动获取焦点
      this.$nextTick(() => {
        this.$refs[`input${index}`].forEach(e => {
          e.focus()
        })
      })
    },
    saveFileName (fileItem) {
      // 保存文件名的逻辑
      fileItem.filename = this.newFilename
      updateFilename(fileItem.id, fileItem.filename).then(res => {
        if (res.code == 0) {
          this.$set(fileItem, 'fileName', this.newFilename)
          this.$set(fileItem, 'isEditor', false)
        } else {
          this.$message.error('修改文件名称错误')
        }
      })
    },
    // 在 saveFileName 方法中更新文件名并退出编辑模式
    handleClick (fileItem, index) {
      // 模拟双击事件
      if (this.clickTimeout) {
        clearTimeout(this.clickTimeout)
        this.clickTimeout = null
        this.handleDoubleClick(fileItem, index)
      } else {
        this.clickTimeout = setTimeout(() => {
          this.clickTimeout = null
          this.fileView(fileItem)
        }, 300) // 这里的时间间隔可以根据实际情况调整
      }
    },

    /**
     * 流程点击
     */
    startBusinessProcedClick () {
      const confirmTitile = '是否发起监督决定审批?'
      this.$confirm({
        title: '提示',
        content: confirmTitile,
        onOk: () => {
          // 判断对应的校验项是否填写
          return new Promise((resolve, reject) => {
            let validate = true
            // 告知书
            if (!(this.tellFileList && this.tellFileList.length > 0)) {
              validate = false
            }
            if (!this.decisionType) {
              validate = false
            }
            if (this.decisionType == Tp_supervise_decisionValue.SUPPORT) {
              // 通知书
              if (!(this.noticeFileList && this.noticeFileList.length > 0)) {
                validate = false
              }
            }
            if (!this.radioVal) {
              validate = false
            }
            if (!validate) {
              this.$message.error('请填写必填项')
              resolve()
              return
            }
            this.startBusinessProced(resolve)
          }).catch(() => console.log('关闭弹框失败'))
        }
      })
    },
    /**
     * 启动流程
     * @param {}
     * @param {*} callBack
     */
    startBusinessProced (callBack) {
      this.loading = true
      // 启动流程
      const flowParams = {
        applyid: this.applyid, // applyid
        proctype: 'supervise_decision', // 操作分类 复议监督决定的流程变量
        userid: this.currentUser.userId
      }
      const docfield = {}
      if (this.decisionType) {
        docfield.decisiontype = this.decisionType
        docfield.isrectifica = this.radioVal
      }
      console.log('流程入参', flowParams)
      startBusinessProced(flowParams, docfield)
        .then(res => {
          if (res.code !== 0) {
            this.$message.error('操作失败')
          } else {
            this.$message.success('操作成功')
            this.$emit('reload')
            this.$emit('close')
            // 跳转到上一级页面
            this.$router.push({
              path: '/SuperviseTodo/'
            })
          }
        })
        .finnally(() => {
          this.loading = false
          callBack()
        })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/apply/caseProcedure.scss';
</style>

<style lang="less" scoped>
.file_list {
  min-height: 200px;
}

.file_icon {
  font-size: 25px;
}

.file_button {
  display: inline-block;
  margin-right: 20px;
}

.customer_div {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-top: 20px;
}

.customer_span {
  width: 60px;
  font-size: 18px;
}

.customer_input {
  width: 400px;
}

.customer_icon_group {
  margin-left: 30px;
}

.customer_icon {
  font-size: 18px;
  cursor: pointer;
}

.upload-style {
  padding-left: 450px;

  .ant-btn:not([disabled]):hover {
    text-decoration: none;
    margin-left: 0px;
  }

  .ant-upload.ant-upload-select {
    margin-left: 200px;
  }
}

.upload-style-hidden {
  padding-left: 320px;

  .ant-btn:not([disabled]):hover {
    text-decoration: none;
    margin-left: 0px;
  }

  .ant-upload.ant-upload-select {
    margin-left: 200px;
  }

  ::v-deep .ant-upload-list-item-card-actions {
    display: none;
  }
}

.div_center {
  display: flex;
  /*开启flex布局*/
  justify-content: center;
  /*水平居中*/
  align-items: center;
  /*垂直居中*/
  height: 100%;
  /*设置高度*/
}

.progress_success_btn {
  margin-right: 150px;
}

.progress_fail_btn {
  margin-left: 150px;
}

.add_form_btn {
  display: block;
  float: right;
  margin-right: 20px;
}

.add_form_label {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
}

::v-deep .ant-upload-list-text {
  width: 550px;
}
::v-deep .ant-form-item-label {
  > label {
    font-size: 16px;
  }
}

.transparent-input {
  background-color: transparent; /* 设置背景透明 */
  border: none; /* 移除边框 */
  border-bottom: 1px solid rgb(251, 251, 252); /* 可选：添加底部边框以提升可视度 */
  outline: none; /* 移除默认的输入框外观 */
  color: rgb(119, 166, 253); /* 设置文本颜色 */
  /* 可以根据需要添加更多样式 */
}
.upload_text {
  color: #0072c6;
  font-size: 16px;
  font-family: PingFang SC;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  align-self: center;
  width: 100px !important;
}
.pdf_text {
  background: #fff;
  padding: 10px 0;
}

.operate_div {
  display: flex;
  align-items: center;
}

.file_title {
  margin: 20px 0px !important;
  width: 500px;
}

.upload_span {
  min-width: 100px !important;
  display: flex;
  align-items: center;
  /* justify-content: center; */
  // width: 100%;
}
.upload_list_div > a {
  width: 100% !important;
}

.upload_list_div {
  width: 100% !important;
}
</style>
